package com.hn658.base.message.backend.action.appinfo.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.hn658.base.message.app.service.IAppInfoManager;
import com.hn658.base.message.appinfo.entity.AppInfoEO;
import com.hn658.base.message.appinfo.service.IAppInfoService;
import com.hn658.base.message.backend.action.appinfo.IAppInfoAction;
import com.hn658.base.message.backend.action.appinfo.vo.AppInfoRequest;
import com.hn658.base.message.backend.action.appinfo.vo.QueryAppInfoResponse;
import com.hn658.base.message.common.utils.DateUtil;
import com.hn658.framework.common.AbstractBaseService;
import com.hn658.framework.common.IServiceResponse;
import com.hn658.framework.common.ResponseStatus;
import com.hn658.framework.dataaccess.pagination.GenericPage;
import com.hn658.framework.shared.exception.BusinessException;
import com.hn658.framework.shared.utils.BeanMapper;
import com.hn658.user.itf.vo.AppInfoDTO;

/**
 * Created by baihai on 2015/8/26.
 */
@Controller("appInfoAction")
@Path("appinfo")
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")
public class AppInfoActionImpl extends AbstractBaseService implements IAppInfoAction{

	/**
	 * 应用MQ管理app信息service
	 */
    @Autowired
    private IAppInfoService appInfoService;
    /**
     * 基础应用管理平台查询app信息service
     */
    @Autowired
    private IAppInfoManager appInfoManager;
    @Path("queryAppInfo")
    @Consumes("application/x-www-form-urlencoded; charset=UTF-8")
    @Produces("application/json; charset=UTF-8")
    @POST
    public IServiceResponse queryAppInfo(
            @FormParam(value="appId") String appId,
            @FormParam(value="appName") String appName,
            @FormParam(value="appNameLike") String appNameLike,
            @FormParam(value="createStartTime") String createStartTime,
            @FormParam(value="createEndTime") String createEndTime,
            @FormParam(value="limit") int limit,
            @FormParam(value="start") int start) throws Exception {
        QueryAppInfoResponse response = new QueryAppInfoResponse();
        Map<String,Object> params=new HashMap<String, Object>();
        if(StringUtils.isNotBlank(appId)){
            params.put("appId", appId);
        }
        if(StringUtils.isNotBlank(appName)){
            params.put("appName", appName);
        }
        if(StringUtils.isNotBlank(appNameLike)){
        	params.put("appNameLike", appNameLike);
        }
        try {
            params.put("createStartTime",
                    StringUtils.isEmpty(createStartTime)?null:
                            DateUtils.parseDate(createStartTime, "yyyy-MM-dd"));
            params.put("createEndTime",
                    StringUtils.isEmpty(createEndTime)?null:
                            DateUtil.oneDateLastTime(DateUtils.parseDate(createEndTime, "yyyy-MM-dd")));
            GenericPage<AppInfoEO> genericPage =  appInfoService.queryAppInfo(params,limit,start,"create_time",false);
            response.setAppInfoList(genericPage.getData());
            response.setTotalCount(genericPage.getTotalCount());
            this.success(response);
        } catch (BusinessException e) {
            this.error(response, e);
        }
        return response;
    }


    /**
     * 增加应用信息
     * @return
     */
    @Path("addAppInfo")
    @Consumes("multipart/form-data; charset=UTF-8")
    @POST
    public IServiceResponse addAppInfo(@Multipart(value="appId") String appId,
    		@Multipart(value="appName", required=true) String appName,
    		@Multipart(value="descInfo", required=false) String descInfo,
    		@Multipart(value="baiduApiKey", required=true) String baiduApiKey,
    		@Multipart(value="baiduSecretKey", required=true) String baiduSecretKey,
    		@Multipart(value="apnsPath", required=false) String apnsPath,
    		@Multipart(value="apnsPassword", required=true) String apnsPassword,
    		@Multipart(value="apnsUpload", required=true) byte[] apnsUpload,
    		@Context HttpServletRequest request){
        QueryAppInfoResponse response = new QueryAppInfoResponse();
        try {
        	AppInfoEO appInfoEO=new AppInfoEO();
        	appInfoEO.setAppId(appId);
        	appInfoEO.setAppName(appName);
        	appInfoEO.setDescInfo(descInfo);
        	appInfoEO.setBaiduApiKey(baiduApiKey);
        	appInfoEO.setBaiduSecretKey(baiduSecretKey);
        	appInfoEO.setApnsPath(apnsPath);
        	appInfoEO.setApnsPassword(apnsPassword);
            appInfoService.addApp(appInfoEO,apnsUpload);
            this.success(response);
        } catch (BusinessException e) {
            this.error(response, e);
            if (e.getErrorMsg()==e.getErrorCode()) {
                response.setResponseStatus(new ResponseStatus(e.getErrorCode(), e.getErrorMsg()));
            }
        }
        return response;
    }

    /**
	 * 修改应用信息
	 * @return
	 */
	@Path("updateAppInfo")
	@Consumes("multipart/form-data; charset=UTF-8")
	@POST
	public IServiceResponse updateAppInfo(@Multipart(value="id") String id,
			@Multipart(value="appId") String appId,
    		@Multipart(value="appName", required=true) String appName,
    		@Multipart(value="descInfo", required=false) String descInfo,
    		@Multipart(value="baiduApiKey", required=true) String baiduApiKey,
    		@Multipart(value="baiduSecretKey", required=true) String baiduSecretKey,
    		@Multipart(value="apnsPath", required=false) String apnsPath,
    		@Multipart(value="apnsPassword", required=true) String apnsPassword,
    		@Multipart(value="apnsUpload", required=true) byte[] apnsUpload,
    		@Context HttpServletRequest request){
		QueryAppInfoResponse response = new QueryAppInfoResponse();
		try{
			AppInfoEO appInfoEO=new AppInfoEO();
        	appInfoEO.setAppId(appId);
        	appInfoEO.setAppName(appName);
        	appInfoEO.setDescInfo(descInfo);
        	appInfoEO.setBaiduApiKey(baiduApiKey);
        	appInfoEO.setBaiduSecretKey(baiduSecretKey);
        	appInfoEO.setApnsPath(apnsPath);
        	appInfoEO.setApnsPassword(apnsPassword);
        	appInfoEO.setId(Long.parseLong(id));
			appInfoService.modifyAppInfo(appInfoEO,apnsUpload);
			this.success(response);
		}catch (BusinessException e) {
			this.error(response, e);
		}
		return response;
	}
	
	@Path("enableAppInfo")
	@POST
	public IServiceResponse enableAppInfo(AppInfoRequest request) {
		QueryAppInfoResponse response = new QueryAppInfoResponse();
		try{
			appInfoService.enableAppInfo(request.getId());
			this.success(response);
		}catch (BusinessException e) {
			this.error(response, e);
		}
		return response;
	}
	
	/**
	 * 禁用应用
	 * @return
	 */
	@Path("disableAppInfo")
	@POST
	public IServiceResponse disableAppInfo(AppInfoRequest request) {
		QueryAppInfoResponse response = new QueryAppInfoResponse();
		try{
			appInfoService.disableAppInfo(request.getId());
			this.success(response);
		}catch (BusinessException e) {
			this.error(response, e);
		}
		return response;
	}

	/**
	 * 查找基础应用管理平台中的app信息
	 * @param appId
	 * @param appNameLike
	 * @param limit
	 * @param start
	 * @return
	 * @throws Exception
	 */
	@Path("findAppInfo")
    @Consumes("application/x-www-form-urlencoded; charset=UTF-8")
    @Produces("application/json; charset=UTF-8")
    @POST
    public IServiceResponse findAppInfo(
            @FormParam(value="appId") String appId,
            @FormParam(value="appName") String appName,
            @FormParam(value="limit") int limit,
            @FormParam(value="start") int start) throws Exception{
		QueryAppInfoResponse response = new QueryAppInfoResponse();
		Map<String, Object> params=new HashMap<String, Object>();
		try{
			if(StringUtils.isNotBlank(appId)){
	            params.put("appId", appId);
	        }
			if(StringUtils.isNotBlank(appName)){
				params.put("appNameLike", appName);
			}
			GenericPage<AppInfoDTO> appInfoPage = appInfoManager.findAppInfo(params, limit, start);
			List<AppInfoEO> mapList=null;
			if(appInfoPage.getData()!=null){
				mapList = BeanMapper.mapList(appInfoPage.getData(), AppInfoEO.class);
			}
			response.setAppInfoList(mapList);
			response.setTotalCount(appInfoPage.getTotalCount());
			 this.success(response);
	    } catch (BusinessException e) {
	        this.error(response, e);
	    }
	    return response;
	}
}
